# -*- coding: utf-8 -*-

import os
import gtk
import gobject

import Plugin
import desktop
from emesenelib.common import escape
from emesenelib.common import unescape
from Parser import PangoDataType

ERROR = ''

class MainClass(Plugin.Plugin):
    '''Main plugin class'''
    description = _('Plugin that use Kdialog to advice you of a' \
    					+ 'new event (connection, message, ...)')
    authors = {'Cruster': 'pkoutsias@gmail.com', 'Version' : '0.5', 'Based on': "Tito's AbsoluteNotify"}
    website = ''
    displayName = _('Knotify')
    name = 'Knotify'

    def __init__(self, controller, msn):
        '''Contructor'''
        #Some usefull things
        Plugin.Plugin.__init__(self, controller, msn, 1000)
        self.controller = controller
        self.description = _('Plugin that use Kdialog to advice you of a' \
                              + 'new event (connection, message, ...)')
        self.authors = {'Cruster': 'pkoutsias@gmail.com', 'Version' : '0.5', 'Based on': "Tito's AbsoluteNotify"}
        self.website = ''
        self.displayName = _('Knotify')
        self.name = 'Knotify'
        self.enabled = False
        self.connected = []
        self.notifications = []
        self.config = controller.config
        self.config.readPluginConfig(self.name)
        
        self.defaultIcon = self.controller.theme.getImage('userPanel')
        self.tray = self.controller.trayIcon.getNotifyObject()

        #Signals
        self.signals = {
            'switchboard::message' : ['message', _('Notify when receiving a message'), self.message],
            'switchboard::typing' : ['typing', _('Notify when someone is typing *(not working well)*'), self.typing],
            'switchboard::nudge': ['nudge', _('Notify when someone nudges you'), self.nudge],
            'offline-message-received' : ['offlineMessage', _('Notify when receiving an offline message'), self.offlineMessage],
            'user-online' : ['online', _('Notify when someone gets online'), self.online],
            'user-offline' : ['offline', _('Notify when someone gets offline'), self.offline],
            'new-mail-notification' : ['mail', _('Notify when receiving a new e-mail'), self.mail],
            'contact-status-change' : ['status', _('Notify when someone changes his status'), self.status] }
        
        self.status = {
            'NLN' : _('online'),
            'FLN' : _('offline'),
            'AWY' : _('away'),
            'BSY' : _('busy'),
            'BRB' : _('be right back'),
            'PHN' : _('on the phone'),
            'LUN' : _('gone to lunch'),
            'IDL' : _('idle')
        }

    def start(self):
        '''Connects to wanted signals'''
        self.enabled = True
        if int(self.config.getPluginValue(self.name, 'alreadyConfigured', 0)) == 0:
            self.configure()
        else:
            for (signal, translation) in self.signals.items():
                if bool(int(self.config.getPluginValue(self.name, translation[0], 0))):
                    self.connected.append(self.msn.connect(signal, translation[2]))
    
    def stop(self):
        for i in self.notifications:
            i.close()
        self.notifications = []
        for toDisconnect in self.connected:
            self.msn.disconnect(toDisconnect)
        self.connected = []
        self.enabled = False
    
    def restart(self):
        self.stop()
        self.start()
    
    def check(self):
        return (True, 'Ok')
        
    def on_notify_close(self, n):
        if n in self.notifications:
            self.notifications.remove(n)
        n.close()
    
    def configure(self):
        '''displays a configuration dialog'''
        l = []
        for signal, translation in self.signals.items():
            l.append(Plugin.Option(translation[0], bool, translation[1], '',
                     bool(int(self.config.getPluginValue(self.name, translation[0], '1')))))
        l.append(Plugin.Option('disableWhileBusy', bool, _('Disable all notifications when busy'), '',
                 bool(int(self.config.getPluginValue(self.name, 'disableWhileBusy', 0)==1))))
                 
        response = Plugin.ConfigWindow(_('Configure Knotify Plugin'), l).run()
        if response != None:
            for signal, translation in self.signals.items():
                if response.has_key(translation[0]):
                    self.config.setPluginValue(self.name, translation[0], str(int(response[translation[0]].value)))
            self.config.setPluginValue(self.name, 'alreadyConfigured', 1)
            self.restart()
        return True
    def stopBusy(self):
        if self.config.getPluginValue(self.name, 'disableWhileBusy', 1) != 0:
            if self.msn.status == 'BSY':
                return True
            else: return False
        else: return False

    def hasFocus(self, mail):
        result = self.controller.conversationManager.getOpenConversation(mail)
        if result != None:
            window, conversation = result
            windowFocus = window.is_active()
            tabFocus = (window.conversation == conversation)
            if windowFocus and tabFocus:
                return True
            else: return False
        else: return False
    
    def window(self):
        return True

    def message(self, msn, switchboard, signal, args, stamp=None):
        if self.stopBusy(): return
        mail, nick, body, format, charset = args
        if self.hasFocus(mail): return
        nick = _('"%s says :"') % self.controller.contacts.get_display_name(mail)
        text = "'" + body + "'"
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True
        
    def typing(self, msn, switchboard, signal, args):
        if self.stopBusy(): return
        mail = args[0]
        if self.hasFocus(mail): return
        nick = "'" + self.controller.contacts.get_display_name(mail) + "'"
        text = _('"Starts typing"')
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True

    def nudge(self, msn, switchboard, signal, args, stamp=None):
        if self.stopBusy(): return
        mail = args[0]
        if self.hasFocus(mail): return
        nick = "'" + self.controller.contacts.get_display_name(mail) + "'"
        text = _('"Has nudged you"')
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True

    def offlineMessage(self, msn, args):
        if self.stopBusy(): return
        mail = args[0]['addr']
        if self.hasFocus(mail): return
        nick = "'" + self.controller.contacts.get_display_name(mail) + "'"
        text = _('"Sent an offline message"')
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True

    def mail(self, msnp, From, FromAddr, Subject, MessageURL, PostURL, id):
        if self.stopBusy(): return
        nick = _('"You got mail"')
        text = 'From :', FromAddr, 'Subj :', Subject
        text = " ".join(["%s" % (k) for k in text])
        text = "'" + text + "'"
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True

    def online(self, msnp, mail, oldStatus):
        if self.stopBusy(): return
        if bool(int(self.config.getPluginValue(self.name, 'contact-status-change', 0))): return
        if oldStatus != 'FLN': return
        nick = "'" + self.controller.contacts.get_display_name(mail) + "'"
        text = _('"Is now online"')
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True

    def offline(self, msn, mail, stamp=None):
        if self.stopBusy(): return
        if bool(int(self.config.getPluginValue(self.name, 'contact-status-change', 0))): return
        nick = "'" + self.controller.contacts.get_display_name(mail) + "'"
        text = _('"Is now offline"')
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True
    
    def status(self, msnp, mail, status):
        if self.stopBusy(): return
        if status == 'FLN' or status == 'NLN': return
        nick = "'" + self.controller.contacts.get_display_name(mail) + "'"
        text = _('"Is now %s"') % self.status[status]
        command = "kdialog", "--title", nick, "--passivepopup", text, 5
        command = " ".join(["%s" % (k) for k in command])
        os.system(command)
        return True